/* Use standard I/O  */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <error.h>
#include <stdbool.h>

/**
* @todo list:input the Bin file,and then output the Bin file's data and length.
* @description: This program is used to read the data and length of a binary file who is MCU's firmware.
* @usage:./ReadFileInformation [BinFileName]
* @author: 52-Hz
* @date: 2024-12-06
* @version: 1.0.0
*/

#define PACKET_MAX_SZIE   64
unsigned char Bindata[PACKET_MAX_SZIE] = {0};

int get_file_length(FILE *filename, unsigned int *length);

int main(int argc, char *argv[])
{
    FILE *OTA_file;
    unsigned int length = 0;
    //1.check whether the input's parameter illegal or not.
    if (argc!= 2)
    {
        fprintf(stderr, "Usage: %s [BinFileName] \r\n", argv[0]);
        exit(EXIT_FAILURE); //exit with error code. EXIT_FAILURE means the program terminated abnormally.
    }
    //2.open the file.
    if ((OTA_file = fopen(argv[1], "rb")) == NULL)  //"rb" means read binary file.
    {
        perror("can't open file");
        exit(EXIT_FAILURE);
    }
    //3.read the file's data and length.
    get_file_length(OTA_file,&length);//get the length of the file.
    //3.2 read the file's data.
    // while(( ch = getc(OTA_file))!= EOF) //EOF means end of file.
    // {
    //     putc(ch, stdout);
    // }
    fread(Bindata, 1, PACKET_MAX_SZIE, OTA_file);
    //4.close the file.
    if(fclose(OTA_file) != 0) //close the file.
    {
        perror("can't close file");
        exit(EXIT_FAILURE);
    }
    printf("\nThe length of the file is %d \r\n", length);
    //display the part of the file's data.
    for(int i=0;i<PACKET_MAX_SZIE;i++){
        printf("Bindata[%d]=%02x ",i,Bindata[i]);
    }
    return 0;
}


int get_file_length(FILE *filename, unsigned int *length)
{
    int ret = false;
    fseek(filename, 0, SEEK_END); //move the file pointer to the end of the file.
    *length = ftell(filename); //get the current position of the file pointer, which is the length of the file.
    fseek(filename, 0, SEEK_SET); //move the file pointer to the beginning of the file.
    ret = true;

    return ret;
}